﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.Service.Helper;
using ORS.OrderRobot.ServiceContracts;

namespace ORS.OrderRobot.Service.Worker
{
    public class AccountLoginWorker : CronWorkerBase, IBackgroundWorker, IScoped
    {
        private readonly ILogger<AccountLoginWorker> _logger;
        private readonly ISystemConfigService _systemConfigService;
        private readonly IAccountLoginService _accountLoginService;
        private readonly IHubContext<MessageHub> _hubContext;
        public AccountLoginWorker(
            ILogger<AccountLoginWorker> logger,
            ISystemConfigService systemConfigService,
            IAccountLoginService accountLoginService,
            IHubContext<MessageHub> hubContext
        )
        {
            _logger = logger;
            _systemConfigService = systemConfigService;
            _accountLoginService = accountLoginService;
            _hubContext = hubContext;
        }

        public override string Name => nameof(AccountLoginWorker);

        public override async Task<string> GetCronExpressionAsync()
        {
            var configDto = await _systemConfigService.GetConfigAsync();
            var task = configDto.RefreshTokenTask;
            var cron = CronHelper.GetCronByInterval(task.Interval, task.IntervalUnit);
            return cron;
        }

        protected override async Task<TimeOnly?[]> GetTimeRange()
        {
            var configDto = await _systemConfigService.GetConfigAsync();
            return new TimeOnly?[]
            {
                 configDto.RefreshTokenTask.StartTime,
                 configDto.RefreshTokenTask.EndTime,
            };
        }
        protected override async Task DoWorkAsync()
        {
            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = "自动登录器",Action = "登录开始"});
            var configDto = await _systemConfigService.GetConfigAsync();
            if (configDto.RefreshTokenTask.Disabled)
            {
                _logger.LogWarning("用户自动登录任务已禁用");
                await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = "自动登录器",Action = "登录被禁用",Type = Consts.ErrMsg});
            }
            var list = await _accountLoginService.AutoLoginAsync();
            await MsgHelper.SendAsync(_hubContext,new MsgData { Obj = "自动登录器",Action = "登录完成"});
        }
    }
}

